import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { maskPhoneNumber, setTabBarIndex } from '../../utils/hooks';
import * as Storage from '../../utils/storage';
import { getQrcode } from '../../utils/util';
const $api = require('../../request/api').API;
const app = getApp();
Page({
  data: {
    userName: '',
    avatarUrl: '',
    showBindgPhone: false,
    userPhone: '',
    phone: '',
    vaguePhone: '',
    code: '',
    second: '',
    detailRole: '',
    level: '',

    username: '',
    password: '',
    showApply: false,
    codeUrl: '',
    showCode: false,

    qrcode: '',
    // isAuth:false,
    type: '',
    smsType: 103,
    salePhone: '',
    title: '绑定手机号'
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    setTabBarIndex(4);
    const phone = wx.getStorageSync(Storage.PHONE);
    this.setData({
      userName: wx.getStorageSync('nickName'),
      avatarUrl: wx.getStorageSync('avatarUrl'),
      detailRole: wx.getStorageSync(Storage.DETAIL_ROLE),
      level: wx.getStorageSync(Storage.LEVEL),
      vaguePhone: phone ? maskPhoneNumber(phone) : '',
      userPhone: phone || ''
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  async onReady() {
    await this.getSalePhone();
    if (!this.data.vaguePhone) {
      this.setData({
        type: 1,
        showBindgPhone: true
      });
    }
    this.getQrcode();
  },
  getQrcode() {
    getQrcode('#myQrcode', wx.getStorageSync(Storage.ACCESS_TOKEN)).then(res => {
      this.setData({
        qrcode: res
      });
    });
  },
  // // 判断是否认证资质
  // async judgeAuth(){
  //     const res = await $api.accountInfo({userId:wx.getStorageSync(Storage.USER_ID)})
  //     this.setData({
  //       isAuth:res.data.data?true:false
  //     })
  // },
  //预览二维码
  previewQrcode() {
    const { qrcode } = this.data;
    wx.previewImage({
      urls: [qrcode],
      current: qrcode
    });
  },
  checkCode(e) {
    const { type } = e.currentTarget.dataset;
    if (type == 1) {
      // 自身二维码
      this.setData({
        codeUrl: this.data.qrcode,
        showCode: true
      });
      return;
    }
    Toast.loading({
      message: '生成推广码中...',
      mask: true,
      forbidClick: true
    });
    $api.getPromoteCode().then(res => {
      Toast.clear();
      this.setData({
        showCode: true,
        codeUrl: res.data.data
      });
    });
    // wx.navigateTo({
    //   url: '/pages/person/authPromoter/index',
    // })
    // wx.navigateTo({
    //   url: '/pages/person/authApply/index',
    // })
  },
  closeCode() {
    this.setData({
      showCode: false
    });
  },
  // 去小区列表页面
  toVillageList() {
    wx.navigateTo({
      url: '/subcontract/person/pages/villageList/index'
    });
  },
  // 去推广员列表页面
  toPromoterList() {
    wx.navigateTo({
      url: '/subcontract/person/pages/promoterList/index'
    });
  },
  // 去申请码管理页面
  toApplayCode() {
    wx.navigateTo({
      url: '/subcontract/person/pages/applayCode/index'
    });
  },
  toTest() {
    wx.navigateTo({
      url: '/subcontract/person/pages/monthBill/index'
    });
  },
  // 设置用户昵称头像
  setUserInfo() {
    let params = {
      nickName: this.data.userName,
      avatarUrl: this.data.avatarUrl
    };
    this.selectComponent('#user-info').showPopup(params);
  },
  // 组件设置用户信息成功后
  getUserInfo(val) {
    this.setData({
      userName: val.detail.nickName,
      avatarUrl: val.detail.avatarUrl
    });
  },
  // 去收货地址列表
  toAddressList() {
    wx.navigateTo({
      url: '/subcontract/person/pages/addressList/index'
    });
  },
  // 去呼叫器地址页面
  toBeeperAddress() {
    wx.navigateTo({
      url: '/subcontract/person/pages/beeperAddress/index'
    });
  },
  // 前往积分管理
  toPointsManagement() {
    wx.navigateTo({
      url: '/subcontract/person/pages/pointsManagement/index'
    });
  },
  /**
   * 社区管理 前往h5系统
   */
  toCommunityManagement() {
    const user_id = wx.getStorageSync(Storage.USER_ID);
    const url = encodeURIComponent(`https://kics.kanglailab.com/home?userId=${user_id}`);
    wx.navigateTo({
      url: `/subcontract/person/pages/h5Page/index?url=${url}`
    });
  },
  bindContacts() {
    wx.navigateTo({
      url: '/subcontract/person/pages/contacts/index'
    });
  },
  inputChange(e) {
    const prop = e.currentTarget.dataset.prop;
    this.setData({
      [prop]: e.detail.value
    });
  },
  async getUserPhone() {
    const res = await $api.getUserPhone();
    const data = res.data.data;
    let vaguePhone = '';
    if (data) {
      const temp = data.split('');
      temp.splice(3, 4, '****');
      vaguePhone = temp.join('');
    }
    const phone = data ? data : '';
    this.setData({
      phone,
      userPhone: phone,
      vaguePhone
    });
  },
  async getSalePhone() {
    const res = await $api.getSalePhone();
    this.setData({
      salePhone: res.data.data || ''
    });
  },
  bindingPhone(e) {
    const { type, sms } = e.currentTarget.dataset;
    this.setData({
      showBindgPhone: true,
      phone: type == 1 ? this.data.userPhone : this.data.salePhone,
      title: type == 1 ? (this.data.userPhone ? '更换手机号' : '绑定手机号') : '业务员认证',
      smsType: sms,
      type
    });
  },
  closeBinding() {
    this.setData({
      showBindgPhone: false
    });
  },
  async confirmBinding(e) {
    const { phone, code } = e.detail;
    const params = {
      phone,
      code
    };
    if (this.data.type == 1) {
      await $api.setUserPhone(params);
      Toast.success('绑定成功');
      this.getUserPhone();
    } else if (this.data.type == 2) {
      await $api.bindingCmsSale(params);
      Toast.success('绑定成功');
      wx.setStorageSync(Storage.DETAIL_ROLE, 3);
      this.onLoad();
    }
    this.closeBinding();
  },
  // delContent(e) {
  //   const prop = e.currentTarget.dataset.prop
  //   this.setData({
  //     [prop]: ""
  //   })
  // },
  // // 获取验证码
  // getCode() {
  //   const { phone,smsType } = this.data
  //   const reg = /^1(3|4|5|6|7|8|9)\d{9}$/
  //   if (!phone) {
  //     Toast.fail("请填写手机号")
  //     return
  //   }
  //   if (!reg.test(phone)) {
  //     Toast.fail("手机号码格式不正确")
  //     return
  //   }
  //   const params = {
  //     mobile: phone,
  //     smsType,
  //     useType: 1
  //   }
  //   this.setData({
  //     second: 60
  //   })
  //   this.timer = setInterval(() => {
  //     this.setData({
  //       second: this.data.second - 1
  //     })
  //     if (this.data.second == 0) {
  //       clearInterval(this.timer)
  //     }
  //   }, 1000)
  //   $api.getPhoneCode(params)
  //     .then(res => {
  //       if (res.data.status == 0) {
  //         wx.showToast({
  //           title: '发送验证码成功',
  //           status: 'success'
  //         })

  //       }
  //     });
  // },
  // 去切换用户登录页面
  toLogin() {
    wx.removeStorageSync('beeperCode');
    wx.navigateTo({
      url: '/subcontract/person/pages/login/login/index?isSwitch=true'
    });
  },

  toTaroDemo() {
    wx.navigateTo({
      url: '/taro/pages/index/index'
    });
  },

  // 打客服电话
  callPhone() {
    let phone = '4001512686';
    wx.makePhoneCall({
      phoneNumber: phone, //仅为示例，并非真实的电话号码
      success: function () {
        console.log('拨打电话成功！');
      },
      fail: function () {
        console.log('拨打电话失败！');
      }
    });
  },
  // 资金管理
  toMoneyService() {
    wx.navigateTo({
      url: '/subcontract/person/pages/moneyService/index'
    });
  },
  // 会员余额
  toMemberBalance() {
    wx.navigateTo({
      url: '/subcontract/person/pages/memberBalance/index'
    });
  },
  // 认证开户
  toAuth() {
    wx.navigateTo({
      url: '/pages2/pages/person/authentication/index'
    });
  },
  // 我的账户
  toBindAccount() {
    wx.navigateTo({
      url: '/subcontract/person/pages/bindAccount/index'
    });
  },
  // 去提现
  withdrawal() {
    wx.navigateTo({
      url: '/subcontract/person/pages/withdrawal/index'
    });
  },
  toPerson() {
    wx.navigateTo({
      url: '/subcontract/person/pages/personInfo/infoIndex/index'
    });
  }
});
